package biz.yfsoft.app.fastframework.admin;

import java.util.Arrays;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class PermissionController extends AdminController {
	
	@Override
	protected String getTable() {
		return "sys_permission";
	}
	
	public void index() {
		render("/admin/users/permission.jsp");
	}
	
	public void clearPermmison(String roleid){
		
		Db.deleteById("sys_role_permission", "roleid", roleid);
	}
	
	@Override
	protected String getSearchFields(String searchs) {
		if(isSqlInject(searchs)){
			return " 1 = 2 ";
		}
		
		if(searchs == null){
			return " 1 = 1 ";
		}
		return " name like '%{key}%' or title like '%{key}%'".replace("{key}", searchs);
	}
	
	public void save(){
		String roleid = this.getPara("roleid");
		String[] permissionid = this.getParaValues("permissionid");
		if(permissionid == null){
			//未选择任何权限
			//删除该角色的权限
			clearPermmison(roleid);
			renderJson(this.wrapJson(0));
			return;
		}
		if(permissionid.length<1){
			clearPermmison(roleid);
			renderJson(this.wrapJson(0));
			return;
		}else{
			String arrPermission = Arrays.toString(permissionid).replace("[", "").replace("]", "").replace(" ", "");
			//修改权限
			Record permission = Db.findFirst("select * from  sys_role_permission where roleid = ?",roleid);
			if(permission == null){
				//新增权限
				permission = new Record();
				permission.set("roleid", roleid);
				permission.set("permissionid",arrPermission);
				Db.save("sys_role_permission", permission);
			}else{
				permission.set("permissionid",arrPermission);
				Db.update("sys_role_permission", permission);
			}
		}
		renderJson(this.wrapJson(0));
		
	}
	
	public void ajax(){
		String roleid = getPara(0,null);
		if(StrKit.isBlank(roleid)){
			renderText("角色不能为空");
			return;
		}
		Record record = Db.findFirst("SELECT * FROM sys_role_permission where roleid=?",roleid);
		renderJson((record != null)?record:new Record());
	}
}
